#coding=utf-8
#测试用例标题：阐述用例标题且与用例场景中标题一致
#测试场景：阐述脚本的使用场景
#创建者：陈强
#创建日期：记录脚本的创建日期
#最后修改日期：记录脚本的最后修改日期
#输入参数：描述脚本的输入参数
#输出参数：描述脚本的输出参数
#路径：用例保存的物理路径
from selenium import webdriver
from time import sleep
import time,datetime
import os
import sys
import requests,json,urllib
import re
import pdb
import mysql.connector
import GetHeaders,ID_card,bankid
import urllib
from urllib import quote
from urllib import unquote
from selenium.webdriver.chrome.options import Options
import connect_mysql
import op_login

#引用connect_mysql程序连接数据库
connect_mysql.connect_mysql()


#新建投资人
def register(url,phone,realname,username,user_password):
    #先通过查询函数查询手机号是否已经注册，若未注册则进入注册流程
    user_id = find_user_id01(url,'10',phone)
    print user_id
    if user_id == u'查无此人，请再次确认所填信息！':
        print u'开始新建投资人'
        import time, datetime
        modify_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))  # 数据产生日期
        import ID_card
        login_headers = {'Referer': 'http://op.'+url, 'Accept-Language': 'zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3',
                         'Upgrade-Insecure-Requests': '1', 'Content-Type': 'application/x-www-form-urlencoded',
                         'Accept-Encoding': 'gzip, deflate',
                         'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:55.0) Gecko/20100101 Firefox/55.0',
                         'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'}
        time = time.strftime("%Y-%m-%d %H:%M", time.localtime(time.time()))
        if url == 'yipaiwang.co':
            adminname = u'陈强'
            password = 'cq123321'
        if url == 'yipaiwang.cc':
            adminname = u'陈强'
            password = 'cq123321'
        if url == 'yidai.co':
            adminname = 'WD108472'
            password = 'jk123123'
        if url == 'yidaip2p.net':
            adminname = u'smilesoul'
            password = 'cq123321'
        userinformation = {'adminname': adminname, 'password': password, 'authCode': '123456'}
        s = requests.session()
        login = s.post('http://op.'+url, data=userinformation, headers=login_headers, verify=False)
        login1 = str(login)
        if u"登录成功" in login.text:
            print login1 + u"登录成功"
            #进行新增投资人操作
            print ID_card.idcard()
            user_data = {'usertype_id':'1','account_type':'10','phone':phone,'realname':realname,'username':username,'id_number':ID_card.idcard(),'province':'2570','city':'2571','address':u'成都市天府广场'}
            user = s.post('http://op.'+url+'/user/addVestMenuUserList/',data=user_data,cookies=login.cookies,headers=login_headers,verify=False)
            #对投资人进行认证操作
            search_data = {'searchType': 'username', 'keywords': username}
            search = s.get('http://op.'+url+'/authrealname/index/',params=search_data,cookies=login.cookies,headers=login_headers,verify=False)
            #通过正则获取到ID号
            res_url = r"(?<=href=\").+?(?=\")|(?<=href=\').+?(?=\')"
            id_url = re.findall(res_url, search.text, re.I | re.S | re.M)  # 取出所有url
            # 循环遍历取出的所有url，并通过判断获得id值
            for id1 in id_url:
                arr = id1.split(',')
                if '/authapproverealname/edit/?id=' in arr[0]:
                    break
            #print str(id1)
            #取出user_id
            res_td = r'<td>(.*?)</td>'
            user_id0 = re.findall(res_td, search.text, re.S | re.M)
            user_id = int(user_id0[0])
            print user_id
            #再通过Chrome headless 模式的无浏览器UI自动化进行密码修改
            chrome_options = Options()
            chrome_options.add_argument('--headless')
            driver = webdriver.Chrome(chrome_options=chrome_options)
            driver.maximize_window()
            driver.implicitly_wait(8)
            driver.get('http://www.'+url+'/user/login/')
            driver.find_element_by_xpath(".//*[@id='submitFrom']/div[3]/div[1]/a").click()
            driver.find_element_by_id("phone_num").send_keys(phone)
            #点击下空白处
            #driver.find_element_by_xpath("html/body/div[2]/div[2]/div/div").click()
            #点击获取验证码按钮
            sleep(2)
            driver.find_element_by_id("send_smscode").click()
            driver.find_element_by_id("smsCode").send_keys('123456')
            driver.find_element_by_xpath(".//*[@id='mobile_findpsw']/div[3]/input").click()
            #输入修改后的密码
            driver.find_element_by_xpath(".//*[@id='forget_step1']/div[1]/div[2]/input").send_keys(user_password)
            driver.find_element_by_xpath(".//*[@id='forget_step1']/div[2]/div[2]/input").send_keys(user_password)
            driver.find_element_by_xpath(".//*[@id='forget_step1']/div[3]/input").click()
            driver.quit()
            # 进行数据库写入
            connect = connect_mysql.connect_mysql()[0]  # connect是由connect_mysql函数返回的第一个值
            cursor = connect.cursor()
            # SQL 插入语句
            sql = "insert into mysql.user_information(user_id,url,username,password,nickname,phone,id_number,modify_time) values('%s','%s','%s','%s','%s','%s','%s','%s')" % (str(user_id),url, realname,user_password,username,phone,ID_card.idcard(),modify_time)
            print sql
            # 执行sql语句
            input = cursor.execute(sql)
            connect.commit()  # 实例提交命令
            # cursor.close()
            # connect.close()
            print("insert ok")
            return u'真实姓名：'+'【'+realname+'】'+u'昵称：'+'【'+username+'】'+u'user_id：'+'【'+str(user_id)+'】'+u'身份证号码是：'+'【'+ID_card.idcard()+'】'+u'手机号码是：'+'【'+phone+'】'+u'默认密码为：'+user_password

        else:
            return u"登录失败,请确认账号和密码是否匹配"
    else:
        return u'该手机号已注册！请更换手机号码！'



#此程序为先利用Chrome headless 模式进行登录操作，获取到headers和cookies后进行的接口自动化程序
def bangka(url,keywords,password,realname):
    login_headers = {'Referer': url+'/user/login/', 'Accept-Language': 'zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3',
                     'Upgrade-Insecure-Requests': '1', 'Content-Type': 'application/x-www-form-urlencoded',
                     'Accept-Encoding': 'gzip, deflate',
                     'User-Agent': 'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/538.1 (KHTML, like Gecko) PhantomJS/2.1.1 Safari/538.1',
                     'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'}
    bank_headers = {'Referer': url + '/bankmanage/addBank/',
                     'Accept-Language': 'zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3',
                     'Upgrade-Insecure-Requests': '1', 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
                     'Accept-Encoding': 'gzip, deflate',
                     'User-Agent': 'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/538.1 (KHTML, like Gecko) PhantomJS/2.1.1 Safari/538.1',
                     'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'}
    now = time.strftime("%d%H%M%S", time.localtime(time.time()))  # 邮箱和紧急联系人号码格式
    print u'开始进行新用户实名认证+风险测评+邮箱认证+紧急联系人添加操作'
    try:
        chrome_options = Options()
        chrome_options.add_argument('--headless')
        driver = webdriver.Chrome(chrome_options=chrome_options)
        id_number = ID_card.idcard()
        bank_card = bankid.bank_card()
        #通过函数获取到登录后的cookies
        cookies = GetHeaders.login_headers(url,keywords,password)
        s = requests.session()
        index = s.get(url+'/userindex/',cookies=cookies,headers=login_headers,verify=False)
        addBank = s.get(url+'/bankmanage/addBank/',cookies=cookies,headers=login_headers,verify=False)
        #登录成功后，进入绑卡操作
        ajaxCheck_data = {'card_id': id_number}
        bank_data1 = {'bank_card':bank_card,'id_card':id_number,'real_name':realname,'phone':keywords,'cash':'','bankCode_ips':'4'}
        bank_data2 = {'smscode':'123456','bank_card':bank_card,'idnumber':id_number,'realname':realname,'phone':keywords,'cash':'','bankCode_ips':'4','td':''}
        bank_data3 = {'cash':'iscash'}
        #绑卡第一步
        ajaxCheck = s.get(url+'/setsafe/ajaxCheck/',params=ajaxCheck_data,cookies=cookies,headers=bank_headers,verify=False)
        bangka1 = s.post(url+'/bankmanage/addCard/',data=bank_data1,cookies=cookies,headers=bank_headers,verify=False)
        bangka2 = s.post(url+'/bankmanage/confirmBindCard/',data=bank_data2,cookies=cookies,headers=bank_headers,verify=False)
        bangka3 = s.post(url+'/deposit/ajaxInfo/',data=bank_data3,cookies=cookies,headers=bank_headers,verify=False)
        # 进行邮箱认证
        email_index = s.get(url + '/setsafe/ipaemail/', cookies=cookies, headers=login_headers, verify=False)
        email = str(now) + '@163.com'
        email = quote(str(email))
        email = unquote(email)
        email_data = {'email': (None, email)}
        email_submit = s.get(url + '/setsafe/ajaxCheckEmail/?email=' + email, cookies=cookies, headers=login_headers,verify=False)
        email_submit = s.get(url + '/setsafe/ajaxCheckEmail/?email=' + email, cookies=cookies, headers=login_headers,verify=False)
        emai_sub_ipaemail = s.post(url + '/setsafe/sub_ipaemail/', data=email_data, cookies=cookies,headers=login_headers, verify=False)
        email_second = s.get(url + '/setsafe/ipaemail_second/', cookies=cookies, headers=login_headers, verify=False)
        email_third = s.get(url + '/setsafe/ipaemail_second/?frm=1', cookies=cookies, headers=login_headers,verify=False)
        # 添加紧急联系人
        sublinkman_data = {'realName': (None, u'陈啦啦'), 'mobile': (None, '138' + str(now)), 'relation': (None, '5')}
        phone = '138'+str(now)
        sublinkman_submit = s.post(url + '/setsafe/sublinkman/', data=sublinkman_data, cookies=cookies,headers=login_headers, verify=False)
        #绑卡完成后进行风险测评
        if url == 'http://www.yipaiwang.co' or 'http://www.yipaiwang.cc':
            setsafe = s.get(url+'/setsafe/riskassessment/',cookies=cookies,headers=login_headers,verify=False)
            setsafe_date = {'risk_type':'4','scores':'1|4|4|4|4|4|4|4|4|4|'}
            setsafe_submit = s.post(url+'/setsafe/risksubmit/',data=setsafe_date,cookies=cookies,headers=login_headers,verify=False)
        if url == 'http://www.yidai.co' or 'http://www.yidaip2p.net':
            setsafe = s.get(url + '/setsafe/riskassessment/', cookies=cookies, headers=login_headers, verify=False)
            setsafe_date = {'risk_type': '5', 'scores': '-3|10|10|10|10|10|10|10|10|15|','checked_option':'4|5|4|4|5|4|4|4|3|5|'}
            setsafe_submit = s.post(url + '/setsafe/risksubmit/', data=setsafe_date, cookies=cookies,headers=login_headers, verify=False)
        #确认已经风险测评完毕，并且为积极型
        if '积极型' or '激进型' in setsafe_submit.text:
            driver.quit()
            # 进行数据库写入
            connect = connect_mysql.connect_mysql()[0]  # connect是由connect_mysql函数返回的第一个值
            cursor = connect.cursor()
            # SQL 插入语句
            #sql = "update mysql.user_information(bank_card,email,friendname,friendphone) values('%s','%s','%s','%s')" % (bank_card, email,u'陈啦啦','138'+str(now))
            sql = "update mysql.user_information set id_number='"+id_number+"', bank_card ='"+bank_card+"',email ='"+email+"',friendname='陈啦啦',friendphone='"+phone+"' WHERE phone = '"+keywords+"'"
            print sql
            # 执行sql语句
            input = cursor.execute(sql)
            connect.commit()  # 实例提交命令
            # cursor.close()
            # connect.close()
            print("update ok")
            return u"实名认证+绑卡成功，身份证是："+id_number+u"，银行卡号是："+bank_card+u'，风险测评结果为：积极型'+u'，邮箱添加成功：'+ email +u'，紧急联系人姓名：陈啦啦，号码：'+phone
        else:
            driver.quit()
            return u"风险测评失败"
    except:
        driver.quit()
        return u"请确认信息无误后再次提交！"


#输入手机号码，查询出用户的user_id
def find_user_id(url,usertype,phone):
    #引用运营系统登录函数op_login
    s = op_login.login(url)[1]
    login_status = op_login.login(url)[0]
    cookies = op_login.login(url)[2]
    headers = op_login.login(url)[3]
    if login_status == '0':
        print u"登录成功"
        #进行搜索该用户的user_id
        try:
            search_data = {'searchType':'phone','userSearchType':usertype,'searchInput':phone}
            search = s.get('http://op.' + url+'/user/menuUserList/',params=search_data,cookies=cookies,headers=headers,verify=False)
            # 正则表达式获取<td></td>之间内容
            res_tr = r'<td>(.*?)</td>'
            m_tr = re.findall(res_tr, search.text, re.S | re.M)
            user_id = m_tr[0]
            nickname = m_tr[1]
            user_type = m_tr[2]
            user_phone = m_tr[4]
            user_terminal = m_tr[5]
            register_time = m_tr[6]
            recharge_status = m_tr[7]
            user_status = m_tr[9]
            if user_phone == phone:
                print u'该用户ID是：'+user_id+u'，昵称是：'+nickname+u'，账户类型是：'+user_type+u'，注册终端是：'+user_terminal+u'，注册时间是：'+register_time+u'，是否充值：'+recharge_status+u'，账号状态为：'+user_status
                return u'该用户ID是：'+user_id+u'，昵称是：'+nickname+u'，账户类型是：'+user_type+u'，注册终端是：'+user_terminal+u'，注册时间是：'+register_time+u'，是否充值：'+recharge_status+u'，账号状态为：'+user_status
            else:
                return u'查无此人，请再次确认所填信息！'
        except:
            return u'查无此人，请再次确认所填信息！'

    else:
        return u'登录失败，账号密码不匹配！请联系陈强进行修改！'

#输入手机号，返回用户的user_id
def find_user_id01(url,usertype,phone):
    # 引用运营系统登录函数op_login
    s = op_login.login(url)[1]
    login_status = op_login.login(url)[0]
    cookies = op_login.login(url)[2]
    headers = op_login.login(url)[3]
    if login_status == '0':
        print u"登录成功"
        #进行搜索该用户的user_id
        try:
            search_data = {'searchType':'phone','userSearchType':usertype,'searchInput':phone}
            search = s.get('http://op.' + url+'/user/menuUserList/',params=search_data,cookies=cookies,headers=headers,verify=False)
            # 正则表达式获取<td></td>之间内容
            res_tr = r'<td>(.*?)</td>'
            m_tr = re.findall(res_tr, search.text, re.S | re.M)
            user_id = m_tr[0]
            nickname = m_tr[1]
            user_type = m_tr[2]
            user_phone = m_tr[4]
            user_terminal = m_tr[5]
            register_time = m_tr[6]
            if user_phone == phone:
                print u'该用户ID是：'+user_id+u'，昵称是：'+nickname+u'，账户类型是：'+user_type+u'，注册终端是：'+user_terminal+u'，注册时间是：'+register_time
                return user_id
            else:
                return u'查无此人，请再次确认所填信息！'
        except:
            return u'查无此人，请再次确认所填信息！'

    else:
        return u'登录失败，账号密码不匹配！请联系陈强进行修改！'

#发放红包的程序
def Redenvelopes(url,envelopes_id,phone,laiyuan):
    #通过查询函数获取到user_id
    user_id = find_user_id01(url,'10',phone)
    try:
        #判断该手机号是否已经注册
        if user_id == u'查无此人，请再次确认所填信息！':
            return u'查无此人，请再次确认所填信息！'
        else:
            # 引用运营系统登录函数op_login
            s = op_login.login(url)[1]
            login_status = op_login.login(url)[0]
            cookies = op_login.login(url)[2]
            headers = op_login.login(url)[3]
            if login_status == '0':
                print u"登录成功"
                # 进行手动发红包流程
                Redenvelopes_data = {'id[]':envelopes_id,'cname':laiyuan,'uploadType':'name','text-username':user_id}
                Redenvelopes = s.post('http://op.' + url+'/redenvelopeissue/add/',data=Redenvelopes_data,cookies=cookies,headers=headers,verify=False)
                #根据所填的来源进行查询红包记录
                search_data = {'source_name':laiyuan}
                search = s.get('http://op.' + url+'/redenvelopeaudit/index/',params=search_data,cookies=cookies,headers=headers,verify=False)
                #通过正则取出所有的url
                res_url = r"(?<=href=\").+?(?=\")|(?<=href=\').+?(?=\')"
                id_url = re.findall(res_url, search.text, re.I | re.S | re.M)  # 取出所有url
                # 循环遍历取出的所有url，并通过判断获得id值
                for id1 in id_url:
                    arr = id1.split(',')
                    if '/redenvelopeaudit/audit/?id=' in arr[0]:
                        break
                print str(id1)
                id = re.findall(r'(\w*[0-9]+)\w*', id1)  # 从字符串中取出id值
                #通过正则取出token
                shenhe_index_data = {'id':id}
                shenhe_index = s.get('http://op.' + url+'/redenvelopeaudit/audit/',params=shenhe_index_data,cookies=cookies,headers=headers,verify=False)
                token = re.findall(r'<input type="hidden" name="audit_token" value="(.+)">',shenhe_index.text)
                print str(token)
                shenhe_data = {'id':id,'audit_token':str(token),'audit':'ok','audit_remark':'审核成功'}
                shenhe = s.post('http://op.' + url+'/redenvelopeaudit/auditinfo/',data=shenhe_data,cookies=cookies,headers=headers,verify=False)
                #判断是否审核成功
                if '审核成功' in shenhe.text:
                    print u'发放红包成功，红包id为：'+envelopes_id+u'，收到红包的用户id为：'+user_id+u'，收到红包的用户号码为：'+phone
                    return u'发放红包成功，红包id为：'+envelopes_id+u'，收到红包的用户id为：'+user_id+u'，收到红包的用户号码为：'+phone
                else:
                    return u'无此红包！请更换红包序号！'
            else:
                return u'登录失败，账号密码不匹配！请联系陈强进行修改！'
    except:
        return u'无此红包！请更换红包序号！'


#发放加息券的程序
def increasecoupon(url,increasecoupon_id,phone,laiyuan):
    #通过查询函数获取到user_id
    user_id = find_user_id01(url,'10',phone)
    try:
        # 判断该手机号是否已经注册
        if user_id == u'查无此人，请再次确认所填信息！':
            return u'查无此人，请再次确认所填信息！'
        else:
            # 引用运营系统登录函数op_login
            s = op_login.login(url)[1]
            login_status = op_login.login(url)[0]
            cookies = op_login.login(url)[2]
            headers = op_login.login(url)[3]
            if login_status == '0':
                print u"登录成功"
                # 进行手动发红包流程
                Redenvelopes_data = {'id[]':increasecoupon_id,'cname':laiyuan,'uploadType':'name','text-username':user_id}
                Redenvelopes = s.post('http://op.' + url+'/increasecoupon/addUserVestMenuManualSend/',data=Redenvelopes_data,cookies=cookies,headers=headers,verify=False)
                #根据所填的来源进行查询红包记录
                search_data = {'source_name':laiyuan}
                search = s.get('http://op.' + url+'/increasecoupon/MenuManualSend/',params=search_data,cookies=cookies,headers=headers,verify=False)
                #通过正则取出所有的url
                res_url = r"(?<=href=\").+?(?=\")|(?<=href=\').+?(?=\')"
                id_url = re.findall(res_url, search.text, re.I | re.S | re.M)  # 取出所有url
                # 循环遍历取出的所有url，并通过判断获得id值
                for id1 in id_url:
                    arr = id1.split(',')
                    if '/increasecoupon/infoVestMenuManualSend/?id=' in arr[0]:
                        break
                print str(id1)
                id = re.findall(r'(\w*[0-9]+)\w*', id1)  # 从字符串中取出id值
                #通过正则取出token
                shenhe_index_data = {'id':id}
                shenhe_index = s.get('http://op.' + url+'/increasecoupon/auditInfoVestMenuReview/',params=shenhe_index_data,cookies=cookies,headers=headers,verify=False)
                token = re.findall(r'<input type="hidden" name="audit_token" value="(.+)">',shenhe_index.text)
                print str(token)
                shenhe_data = {'id':id,'audit_token':str(token),'audit':'ok','audit_remark':'审核成功'}
                shenhe = s.post('http://op.' + url+'/increasecoupon/doAuditInfoVestMenuReview/',data=shenhe_data,cookies=cookies,headers=headers,verify=False)
                #判断是否审核成功
                if '审核成功' in shenhe.text:
                    print u'发放加息券成功，红包id为：'+increasecoupon_id+u'，收到加息券的用户id为：'+user_id+u'，收到加息券的用户号码为：'+phone
                    return u'发放加息券成功，红包id为：'+increasecoupon_id+u'，收到加息券的用户id为：'+user_id+u'，收到加息券的用户号码为：'+phone
                else:
                    return u'无此加息券！请更换加息券序号！'
            else:
                return u'登录失败，账号密码不匹配！请联系陈强进行修改！'
    except:
        return u'无此加息券！请更换加息券序号！'





if __name__ == '__main__':
    find_user_id('yipaiwang.cc','10','17700020006')









